package com.ktgj.flight.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.enums.EnumHelper;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.flight.common.linkstar.LinkStar;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.IFlightOrderChangeTicketsService;
import com.ktgj.flight.service.IFlightOrderInfoService;
import com.ktgj.flight.service.IFlightOrderInfoTicketsService;
import com.ktgj.flight.service.IFlightOrderQtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Component
public class Scheduler {
    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;

    @Autowired
    private FlightOrderInfoTicketsMapper flightOrderInfoTicketsMapper;

    @Autowired
    private FlightOverdueTicketMapper flightOverdueTicketMapper;

    @Autowired
    private FlightOrderChangeMapper flightOrderChangeMapper;

    @Autowired
    private FlightOrderChangeTicketsMapper flightOrderChangeTicketsMapper;

    private static LinkStar linkStar;

    @Autowired
    public void setLinkStar(LinkStar linkStar){
        Scheduler.linkStar = linkStar;
    }

    @Autowired
    private IFlightOrderInfoService flightOrderInfoService;
    @Autowired
    private IFlightOrderChangeTicketsService flightOrderChangeTicketsService;
    @Autowired
    private IFlightOrderQtService flightOrderQtService;
    @Autowired
    private IFlightOrderInfoTicketsService flightOrderInfoTicketsService;

    /**
     * 订单列表（机票详细-待支付）
     * */
    @Scheduled(fixedDelay = 1000 * 60)
    public void flightOrderInfoOrder(){
        List<FlightOrderInfo> flightOrderInfos = flightOrderInfoMapper.selectFlightOrderInfoByState();
        for (FlightOrderInfo flightOrderInfo : flightOrderInfos) {
            flightOrderInfo.setStatus(CustomerConstants.cancelPay.getValue());
            flightOrderInfo.setGuestPymtStsId(CustomerConstants.cancelPay.getValue());
            flightOrderInfoMapper.updateFlightOrderInfo(flightOrderInfo);
            List<FlightOrderInfoTickets> infoTicketsList = flightOrderInfoTicketsService.selectFlightOrderInfoTicketsByOrderId(flightOrderInfo.getOrderId());
            for (FlightOrderInfoTickets orderInfoTickets : infoTicketsList) {
                orderInfoTickets.setStatus(CustomerConstants.cancelPay.getValue());
                flightOrderInfoTicketsService.updateFlightOrderInfoTickets(orderInfoTickets);
            }
        }
    }

    /**
     * 定时任务-航班信息变动（3分钟抓取一次）
     */
    //TODO 暂时不使用，正式上线后放开
    //@Scheduled(fixedDelay = 3000 * 60)
    public void QMsgSC() {
        XElement xElement = linkStar.QMsg();
        String queueTypeStr = null;
        List<XElement> queue = xElement.elements("Queue");
        for (XElement element : queue) {
            String queueType = element.getAttributeValue("QueueType");
            int total = Integer.parseInt(element.getAttributeValue("Total"));
            if (queueType.equals("SC") && total > 0) {
                queueTypeStr = queueType;
            }
        }
        if (queueTypeStr != null) {
            XElement qMsgSC = linkStar.QMsgSC(queueTypeStr);
            if (qMsgSC.toString().contains("Errors")) {
                return;
            }
            List<XElement> elements = qMsgSC.elements("Queue");
            for (XElement element : elements) {
                XmlMapper xmlMapper = new XmlMapper();
                try {
                    String pnr = xmlMapper.readValue(element.element("QueueInfo").element("Content").toString(), String.class);
                    FlightOrderInfo orderInfo = flightOrderInfoService.queryFlightOrderInfoByPnr(pnr);
                    XElement retByPnrId = linkStar.getOTAAirResRetByPnrId(pnr);
                    if (orderInfo != null) {
                        if (retByPnrId.toString().contains("Errors")) {
                            return;
                        }
                        List<XElement> xElementList = retByPnrId.element("AirResRet").element("FlightSegments").elements("FlightSegment");
                        List<FlightOrderInfoTickets> flightOrderInfoTickets = flightOrderInfoTicketsService.selectOrderInfoTicketByOrderId(orderInfo.getOrderId());
                        xElementList.forEach(item -> {
                            if (item.getAttributeValue("Status").equals("UN")) {
                                List<XElement> xElements = retByPnrId.element("AirResRet").element("AirTraveler").elements("PersonName");
                                xElements.forEach(items -> {
                                    flightOrderInfoTickets.forEach(tickes -> {
                                        try {
                                            if (xmlMapper.readValue(items.element("NamePNR").toString(), String.class).equals(tickes.getGuestName())) {
                                                FlightOrderQt orderQt = new FlightOrderQt();
                                                orderQt.setPassengername(xmlMapper.readValue(items.element("NamePNR").toString(), String.class));
                                                orderQt.setNewTrip(item.element("DepartureAirport").getAttributeValue("LocationCode") + " " + item.element("ArrivalAirport").getAttributeValue("LocationCode"));
                                                orderQt.setAddtime(new Date());
                                                orderQt.setOperationtypeinteger("pending");
                                                orderQt.setTicketcount((long) xElements.size());
                                                orderQt.setQnscConent(String.valueOf(element));
                                                orderQt.setOrderid(String.valueOf(orderInfo.getOrderId()));
                                                orderQt.setDeparturetime(tickes.getDepartureTime());
                                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                String time = item.getAttributeValue("DepartureDateTime");
                                                String[] split = time.split("T");
                                                String newDepTime = split[0] + " " + split[1];
                                                orderQt.setNewDepTime(format.parse(newDepTime));
                                                orderQt.setNewFlight(item.element("MarketingAirline").getAttributeValue("Code") + item.getAttributeValue("FlightNumber"));
                                                orderQt.setIssendmsg("0");
                                                orderQt.setProtect("2");
                                                orderQt.setMobile(orderInfo.getContactMobile());
                                                orderQt.setFlighttrip(item.element("DepartureAirport").getAttributeValue("LocationCode") + " " + item.element("ArrivalAirport").getAttributeValue("LocationCode"));
                                                orderQt.setPnr(orderInfo.getPnr());
                                                if (element.element("QueueInfo").getAttributeValue("QType").equals("8")) {
                                                    orderQt.setChangemessage(xmlMapper.readValue(element.element("QueueInfo").element("Content").toString(), String.class));
                                                } else {
                                                    orderQt.setChangemessage("请维护");
                                                }
                                                orderQt.setFlightno(flightOrderInfoTickets.get(0).getFlight());
                                                flightOrderQtService.insertFlightOrderQt(orderQt);
                                            }
                                        } catch (JsonProcessingException | ParseException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                });
                            }
                        });
                    } else {
                        FlightOrderChangeTickets changeTickets = flightOrderChangeTicketsService.selectOrderChangeTickets(pnr);
                        if (changeTickets != null) {
                            if (retByPnrId.toString().contains("Errors")) {
                                return;
                            }
                            List<XElement> xElementList = retByPnrId.element("AirResRet").element("FlightSegments").elements("FlightSegment");
                            xElementList.forEach(item -> {
                                if (item.getAttributeValue("Status").equals("UN")) {
                                    List<XElement> xElements = retByPnrId.element("AirResRet").element("AirTraveler").elements("PersonName");
                                    xElements.forEach(items -> {
                                        try {
                                            if (xmlMapper.readValue(items.element("NamePNR").toString(), String.class).equals(changeTickets.getGuestName())) {
                                                FlightOrderQt orderQt = new FlightOrderQt();
                                                orderQt.setPassengername(xmlMapper.readValue(items.element("NamePNR").toString(), String.class));
                                                orderQt.setNewTrip(item.element("DepartureAirport").getAttributeValue("LocationCode") + " " + item.element("ArrivalAirport").getAttributeValue("LocationCode"));
                                                orderQt.setAddtime(new Date());
                                                orderQt.setOperationtypeinteger("pending");
                                                orderQt.setTicketcount((long) xElements.size());
                                                orderQt.setQnscConent(String.valueOf(element));
                                                orderQt.setOrderid(changeTickets.getChangeOrderId());
                                                orderQt.setDeparturetime(changeTickets.getDepartureTime());
                                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                String time = item.getAttributeValue("DepartureDateTime");
                                                String[] split = time.split("T");
                                                String newDepTime = split[0] + " " + split[1];
                                                orderQt.setNewDepTime(format.parse(newDepTime));
                                                orderQt.setNewFlight(item.element("MarketingAirline").getAttributeValue("Code") + item.getAttributeValue("FlightNumber"));
                                                orderQt.setIssendmsg("0");
                                                orderQt.setProtect("2");
                                                orderQt.setMobile(changeTickets.getGuestMobile());
                                                orderQt.setFlighttrip(item.element("DepartureAirport").getAttributeValue("LocationCode") + " " + item.element("ArrivalAirport").getAttributeValue("LocationCode"));
                                                orderQt.setPnr(changeTickets.getPnr());
                                                if (element.element("QueueInfo").getAttributeValue("QType").equals("8")) {
                                                    orderQt.setChangemessage(xmlMapper.readValue(element.element("QueueInfo").element("Content").toString(), String.class));
                                                } else {
                                                    orderQt.setChangemessage("请维护");
                                                }
                                                orderQt.setFlightno(changeTickets.getFlight());
                                                flightOrderQtService.insertFlightOrderQt(orderQt);
                                            }
                                        } catch (JsonProcessingException | ParseException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            });
                        }
                    }
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 逾期未起飞客票
     */
    @Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Shanghai")
    public void overdueTicket() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -1);
        date = calendar.getTime();
        String format = dateFormat.format(date);
        List<FlightOrderInfo> flightOrderInfos = flightOrderInfoMapper.overdueTicket(format, format + " 23:59:59");
        if (flightOrderInfos != null && flightOrderInfos.size() > 0) {
            for (FlightOrderInfo flightOrderInfo : flightOrderInfos) {
                List<FlightOrderInfoTickets> infoTicketsList = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(flightOrderInfo.getOrderId());
                for (FlightOrderInfoTickets orderInfoTickets : infoTicketsList) {
                    if (orderInfoTickets.getTicketNo() != null && !orderInfoTickets.getTicketNo().equals("")) {
                        XElement xElement = linkStar.airTicket(orderInfoTickets.getTicketNo());
                        if (xElement.toString().contains("Errors")) {
                            continue;
                        }
                        String ticketStatus = xElement.element("AirTicketRet").element("FlightSegments").element("FlightSegment").getAttributeValue("TicketStatus");
                        if ("OPEN FOR USE".equals(ticketStatus)) {
                            FlightOverdueTicket overdueTicket = new FlightOverdueTicket();
                            overdueTicket.setOrderId(orderInfoTickets.getOrderId().toString());
                            overdueTicket.setPnr(flightOrderInfo.getPnr());
                            overdueTicket.setGuestName(orderInfoTickets.getGuestName());
                            overdueTicket.setDepartureTime(orderInfoTickets.getDepartureTime());
                            overdueTicket.setTicketNo(orderInfoTickets.getTicketNo());
                            calendar = new GregorianCalendar();
                            date = new Date();
                            calendar.setTime(date);
                            calendar.add(Calendar.YEAR, 1);
                            calendar.add(Calendar.DATE, 1);
                            date = calendar.getTime();
                            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            String noInvalidTime = dateFormat.format(date);
                            overdueTicket.setTicketNoInvalidTime(noInvalidTime + " 00:00");
                            overdueTicket.setFlightRoute(orderInfoTickets.getOrgAirport() + " " + orderInfoTickets.getDstAirport());
                            overdueTicket.setFlight(orderInfoTickets.getFlight());
                            overdueTicket.setTicketingPartner("北京分公司");
                            overdueTicket.setRefundStatus("待黑屏");
                            overdueTicket.setNoticeGuestStatus("未发送短信");
                            flightOverdueTicketMapper.insertFlightOverdueTicket(overdueTicket);
                        }
                    }
                }
            }
        }
        List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.overdueTicket(format, format + " 23:59:59");
        if (flightOrderChanges != null && flightOrderChanges.size() > 0) {
            for (FlightOrderChange flightOrderChange : flightOrderChanges) {
                List<FlightOrderChangeTickets> flightOrderChangeTickets = flightOrderChangeTicketsMapper.selectFlightOrderChangeTickets(flightOrderChange.getChangeOrderId());
                for (FlightOrderChangeTickets flightOrderChangeTicket : flightOrderChangeTickets) {
                    XElement xElement = linkStar.airTicket(flightOrderChangeTicket.getTicketNo());
                    if (xElement.toString().contains("Errors")) {
                        continue;
                    }
                    String ticketStatus = xElement.element("AirTicketRet").element("FlightSegments").element("FlightSegment").getAttributeValue("TicketStatus");
                    if ("OPEN FOR USE".equals(ticketStatus)) {
                        FlightOverdueTicket overdueTicket = new FlightOverdueTicket();
                        overdueTicket.setOrderId(flightOrderChangeTicket.getChangeOrderId());
                        overdueTicket.setPnr(flightOrderChangeTicket.getPnr());
                        overdueTicket.setGuestName(flightOrderChangeTicket.getGuestName());
                        overdueTicket.setDepartureTime(flightOrderChangeTicket.getDepartureTime());
                        overdueTicket.setTicketNo(flightOrderChangeTicket.getTicketNo());
                        calendar = new GregorianCalendar();
                        date = new Date();
                        calendar.setTime(date);
                        calendar.add(Calendar.YEAR, 1);
                        calendar.add(Calendar.DATE, 1);
                        date = calendar.getTime();
                        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String noInvalidTime = dateFormat.format(date);
                        overdueTicket.setTicketNoInvalidTime(noInvalidTime + " 00:00");
                        overdueTicket.setFlightRoute(flightOrderChangeTicket.getOrgAirport() + " " + flightOrderChangeTicket.getDstAirport());
                        overdueTicket.setFlight(flightOrderChangeTicket.getFlight());
                        overdueTicket.setTicketingPartner("北京分公司");
                        overdueTicket.setRefundStatus("待黑屏");
                        overdueTicket.setNoticeGuestStatus("未发送短信");
                        flightOverdueTicketMapper.insertFlightOverdueTicket(overdueTicket);
                    }
                }
            }
        }
    }
}